<?php

/**
 * 将藏品上架市场
 * 藏品修改信息
 * 市场列表
 * 上架/ 下架 藏品
 * 上架的详情
 * 2022/3/5 -- by low
 * TODO ::  购买以及往返销售
 */

class Market extends M_Controller
{
    /**
     * 将购买的藏品上架市场
     * 上架之后 默认的商品 status=1
     * 上架完成之后将自己的藏品标记为已上架的状态,无法再次上架 ;此时 视图表会将上架的商品归类
     */
    public function putToMarket()
    {
        try {
            $id = $this->input->get('id');
            if ((int)$id < 1) {
                throw new Exception('参数错误');
            }
            $this->db->trans_begin();
            $info = $this->models('favorite')->cardInfo(['id' => $id], 'id,uid,price,status');
            if (empty($info)) {
                throw new Exception('内容不存在');
            }
            if ($info['uid'] <> $this->uid) {
                throw new Exception('请上架自己的藏品');
            }
            if ($info['status'] > 1) {
                throw new Exception('该物品已处于上架阶段');
            }
            $marketId = $this->models('market')->addGoods([
                'uid' => $info['uid'],
                'price' => $info['price'],
                'cid' => $info['id'],
                'status' => 1
            ]);
            if (empty($marketId)) {
                throw new Exception('上架失败,稍后重试');
            }
            if (empty($this->models('favorite')->operateCard($info['id'], 2))) {
                throw new Exception('更新藏品失败,请稍后重试', 1);
            }
            ### 增加价价格记录
            $this->models('market')->addPriceLog([
                'cid' => $marketId,
                'uid' => $this->uid,
                'price' => $info['price'],
                'time' => time()
            ]);
            $this->db->trans_commit();
            apiSuccess(1, '成功将藏品上架');
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }

    }

    /**
     * 商品的上架/下架
     * 商品状态上架状态为 2
     * 商品下架状态为 1
     * 用户从藏品列表中操作
     * 1 : 初次上架
     * 2:下架
     * 4: 再次上架
     * 3: 卖出
     */
    public function operateGood()
    {
        try {
            $this->db->trans_begin();
            /**
             * @var $goodsInfo
             * @var $info
             */
            $result = $this->cardAndGoods();
            extract($result);
            $msg = $info['status'] == 2 ? '上架' : '下架';
            $status = $info['status'] == 1 ? 2 : 1;
            $cardStatus = $status == 1 ? 2 : 4;
            if (empty($this->models('favorite')->operateCard($goodsInfo['id'], $cardStatus))) {
                throw new Exception('操作失败,请稍后重试');
            }
            if (empty($this->models('market')->operateGood($info['id'], ['status' => $status]))) {
                throw new Exception('操作失败, 请稍后重试', 1);
            }
            $this->db->trans_commit();
            apiSuccess(1, "{$msg}成功");
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    // 更新自己市场中的价格信息
    public function operatePrice()
    {
        try {
            $this->db->trans_start();
            /**
             * @var $goodsInfo
             * @var $info
             * @var $data
             */
            $result = $this->cardAndGoods();
            extract($result);
            if (floatval($data['price']) < 0.01) {
                throw new Exception('请设置正确价格');
            }
            if ($info['status'] == 1) {
                throw new Exception('请先下架再操作');
            }
            if ($info['price'] == $data['price']) {
                throw new Exception('请输入不同价格');
            }
            if (empty($this->models('market')->operateGood($info['id'], ['price' => floatval($data['price'])]))) {
                throw new Exception('更新失败, 请稍后重试');
            }
            ### 增加价格记录
            $this->models('market')->addPriceLog([
                'cid' => $info['id'],
                'uid' => $this->uid,
                'price' => $data['price'],
                'time' => time()
            ]);
            $this->db->trans_complete();
            apiSuccess(1, '成功修改价格');
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 返回藏品和上架信息
     * @throws Exception
     */
    protected function cardAndGoods(): array
    {
        $data = $this->input->post();
        if ((int)$data['id'] < 1) {
            throw new Exception('参数错误');
        }
        $goodsInfo = $this->models('favorite')->cardInfo(['id' => $data['id']], 'id,status,uid');
        if (empty($goodsInfo)) {
            throw new Exception('藏品信息异常,无法操作');
        }
        // 市场
        $info = $this->models('market')->goodInfo(['cid' => $goodsInfo['id']], 'id,lock,status,buy_uid');
        if (empty($info)) {
            throw new Exception('操作市场内容不存在');
        }
        if ($info['buy_uid'] > 0) {
            throw new Exception('商品已被交易,无法修改');
        }
        if ($info['lock'] == 1) {
            throw new Exception('商品处于锁定状态,无法操作');
        }
        return ['goodsInfo' => $goodsInfo, 'info' => $info, 'data' => $data];
    }

    // 市场列表
    public function marketList()
    {
        $param = $this->input->get();
        $page = max($_GET['page'], 1);
        $pageSize = $_GET['pageSize'] ?: 10;
        $order = $this->input->get('order') ?: 'id';
        if (empty((int)$param['cid'])) {
            apiSuccess(0, '请选择分类');
        }
        if (!in_array($order, ['price', 'hits', 'updatetime', 'id'])) {
            apiSuccess(0, '请输入正确的排序');
        }
        $sort = $this->input->get('sort') == 1 ? 'asc' : 'desc';
        $result = $this->models('market')->marketList($param, $page, $pageSize, ['order' => $order, 'sort' => $sort]);
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('market')->goodsTransfer($item);
            }, $result),
            'end' => count($result) < $pageSize
        ]);
    }

    // 市场中商品的详情
    public function goodsInfo()
    {
        $id = $this->input->get('id');
        if ((int)$id < 1) {
            apiSuccess(0, '参数错误');
        }
        $info = $this->models('market')->goodsInfo($id);
        if (empty($info)) {
            apiSuccess(0, '内容不存在');
        }
        apiSuccess(1, 'success', [
            'info' => $this->models('market')->goodsTransfer($info),
            'code' => $this->member['randcode']
        ]);
    }

    // 取出市场内的卡片分类
    public function marketCategory()
    {
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 20;
        $list = $this->models('market')->marketCategory($this->input->get('cid'), $page, $pageSize);
        apiSuccess(1, 'success', [
            'list' => $list ? array_map(function (&$item) {
                return $this->models('market')->goodsTransfer($item);
            }, $list) : [],
            'end' => $pageSize > count($list),
            'category' => $this->models('favorite')->favoriteCategory()
        ]);
    }

    // 首页推荐藏品列表
    public function indexRecommend()
    {
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 10;
        $result = $this->models('market')->getRecommend($page, $pageSize);
        apiSuccess(1, 'success', [
            'list' => $result ? array_map(function (&$item) {
                return $this->models('market')->goodsTransfer($item);
            }, $result) : [],
            'end' => $pageSize > count($result)
        ]);
    }

    // 购买市场内的商品
    public function prepare()
    {
        try {
            /**
             * @var $info
             * @var $number
             * @var $member
             */
            $result = $this->marketInfo();
            extract($result);
            $openID = $this->models('member')->wxInfo($this->uid, 'openid');
            if (empty($openID)) {
                apiSuccess(40003, '无法获取openid');
            }
            apiSuccess(1, 'success', ['info' => $info, 'sn' => $number]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    // 确定购买
    public function buyMarket()
    {
        try {
            $this->db->trans_begin();
            $result = $this->marketInfo();
            $oid = $this->models('market')->addMarketOrder($result);
            if ((int)$oid < 1) {
                throw new Exception('购买商品失败');
            }
            $payID = $this->models('system/pay')->create(
                $this->uid,
                $result['info']['price'],
                'market',
                $oid,
                '购买市场内' . $result['info']['title']
            );
            // 将支付id 更新到订单表
            $this->models('market')->operateOrder($oid, ['pay_id' => $payID]);
            // 确定购买之后将此物锁住, 支付完成后解锁 / 或取消支付 / 或订单超时解锁
            $lockStatus = $this->models('market')->operateLock($result['info']['id'], 1);
            if (empty($lockStatus)) {
                throw new Exception('异常,稍后再试');
            }
            // 加入订单队列
            $this->models('favorite')->addQueue($this->uid, $oid, 'market', $result['info']['id'],
                $result['info']['number']);
            $this->db->trans_commit();
            apiSuccess(1, 'success', ['oid' => $oid, 'payId' => encrypt($payID, 'mutaoinc')]);
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 市场购买所需
     * @throws Exception
     */
    protected function marketInfo(): array
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        ## 查看用户是否是被锁定购买
        $lockStatus = $this->models('favorite')->maxTimeAndNum($this->uid, strtotime("-1 hours"));
        if ($lockStatus['total'] >= 3 && time() - $lockStatus['end'] < 7200) {
            throw new Exception('您在1小时内同一账户产生' . $lockStatus['total'] . '个失效订单,锁定两小时');
        }
        $id = $this->input->get('id');
        if ((int)$id < 1) {
            throw new Exception('市场参数不存在');
        }
        $info = $this->models('market')->goodsInfo($id);
        if (empty($info)) {
            throw new Exception('市场内容不存在');
        }
        if ((int)$info['status'] > 1) {
            throw new Exception('此物品已下架');
        }
        if ($info['lock']) {
            throw new Exception('物品锁定中,无法购买');
        }
        if ($info['buy_uid']) {
            throw new Exception('物品异常,无法购买');
        }
        $member = $this->models('member')->uidInfo(['uid' => $this->uid], 'uid,name,username,team_code');
        $info['author'] = dr_member_info($info['sell_uid'])['username'];
        return ['info' => $info, 'number' => $info['number'], 'member' => $member];
    }

}